package logic

import (
	"strings"

	"gddgame.cc/galaxy/asteroid"
	"gddgame.cc/galaxy/utils/def"
	sys "gddgame.cc/galaxy/utils/system"
	"github.com/antlabs/timer"

	"github.com/pkg/errors"
)

// 管理layer的生成
type Connect struct {
	def.Logger
	timer.Timer
	layers map[string]*asteroid.Layer
}

func NewConnect(logger def.Logger, timer timer.Timer) *Connect {
	return &Connect{
		layers: map[string]*asteroid.Layer{},
		Logger: logger,
		Timer:  timer,
	}
}

func (c *Connect) Layer(node string) *asteroid.Layer {
	if layer, ok := c.layers[node]; ok {
		return layer
	} else {
		return nil
	}
}

func (c *Connect) Connect(node string) (*asteroid.Layer, error) {
	var err error
	var realNode string

	if layer, ok := c.layers[node]; ok {
		return layer, nil
	}

	info := strings.Split(node, ":")
	if len(info) != 2 {
		return nil, NodeFormatError
	}
	if info[0] == "*" || info[0] == "" {
		info[0], err = sys.LocalIPV4()
		if err != nil {
			return nil, err
		}
		realNode = strings.Join(info, ":")
		if realNode == "" {
			return nil, errors.New("[ Connect ] Node is miss")
		}
	} else {
		realNode = node
	}

	layer, err := asteroid.NewLayer(realNode, c.LoggerWrap("asteroid", "layer"), c)
	if err != nil {
		return nil, err
	}
	c.layers[node] = layer
	return layer, nil
}

func (c *Connect) Exit() error {
	for key := range c.layers {
		if err := c.layers[key].Exit(); err != nil {
			return err
		}
	}
	return nil
}
